package drds.plus.common.utils.convertor;

import drds.tools.ShouldNeverHappenException;

import java.util.Collection;
import java.util.Iterator;

/**
 * Collection -> Collection 转化
 */
public class CollectionToCollection extends CollectionAndCollectionConvertor.BaseCollectionConvertor {

    public Object convertCollection(Object src, Class destClass, Class... componentClasses) {
        if (Collection.class.isAssignableFrom(src.getClass()) && Collection.class.isAssignableFrom(destClass)) { // 必须都是Collection
            Collection collection = (Collection) src;
            Collection target = createCollection(destClass);

            boolean isInit = false;
            MappingConfig config = null;

            Class componentClass = null;
            if (componentClasses != null && componentClasses.length >= 1) {
                componentClass = componentClasses[0];
            }

            for (Iterator iter = collection.iterator(); iter.hasNext(); ) {
                Object item = iter.next();
                Class componentSrcClass = item.getClass();

                if (componentClass != null && componentSrcClass != componentClass) {
                    if (isInit == false) {
                        isInit = true;
                        config = initMapping(componentSrcClass, componentClass, componentClasses);
                    }

                    // 添加为mapping convertor
                    target.add(doMapping(item, componentClass, config));
                } else {
                    target.add(item);
                }
            }
            return target;
        }

        throw new ShouldNeverHappenException("Unsupported convert: [" + src + "," + destClass.getName() + "]");
    }

    protected Class getComponentClass(Object src, Class destClass) {
        if (Collection.class.isAssignableFrom(src.getClass()) && Collection.class.isAssignableFrom(destClass)) { // 必须都是Collection
            Collection collection = (Collection) src;
            for (Iterator iter = collection.iterator(); iter.hasNext(); ) {
                Object item = iter.next();
                if (item != null) {
                    return item.getClass();
                }
            }
        }

        return null;
    }
}
